import {js} from "cc";
import {StorageManager} from "db://assets/scripts/common/StorageManager";
import {StorageKey} from "db://assets/scripts/common/StorageKey";
import {Player} from "db://assets/scripts/data/model/Player";

/**
 * 玩家数据管理器
 */
export class PlayerDataManager {
    /**
     * 玩家信息
     */
    private player: Player;

    /**
     * 玩家数据管理器实例
     */
    private static INSTANCE: PlayerDataManager;

    /**
     * 获取玩家数据管理器实例
     */
    public static getInstance(): PlayerDataManager {
        if (this.INSTANCE) {
            return this.INSTANCE;
        }
        this.INSTANCE = new PlayerDataManager();
        return this.INSTANCE;
    }

    private constructor() {
        // 初始化
        this.init();
        // 持久化玩家信息
        this.persistPlayer();
    }

    /**
     * 初始化
     */
    private init() {
        // 初始化玩家
        this.initPlayer();
    }

    /**
     * 初始化玩家
     */
    private initPlayer() {
        // 老玩家
        let json = StorageManager.getInstance().getData(StorageKey.PLAYER);
        if (json) {
            this.player = JSON.parse(json);
            // 更新时间
            this.player.updateTime = new Date();
            return;
        }

        // 新玩家
        this.player = {
            id: js.IDGenerator.global.getNewId(),
            createTime: new Date(),
            updateTime: new Date(),
            nickname: "玩家",
            level: 1,
            gold: 0,
            diamond: 0,
            key: 0,
            floor: 1,
            heightFloor: 1,
            skillIds: [],
        };
    }

    /**
     * 持久化玩家信息
     */
    public persistPlayer() {
        // 保存玩家信息
        StorageManager.getInstance().setData(StorageKey.PLAYER, JSON.stringify(this.player));
    }

    /**
     * 更新玩家信息
     * 例如钻石、金币、道具
     */
    public updatePlayer(player: Player) {
        // 修改玩家信息
        this.player.updateTime = new Date();
        this.player.nickname = player.nickname;
        this.player.level = player.level;
        this.player.gold = player.gold;
        this.player.diamond = player.diamond;
        this.player.key = player.key;
        this.player.floor = player.floor;
        this.player.heightFloor = player.heightFloor;
        this.player.skillIds = player.skillIds;
        // 保存玩家信息
        this.persistPlayer();
    }

    /**
     * 删除玩家信息
     */
    public deletePlayer() {
        StorageManager.getInstance().deleteData(StorageKey.PLAYER);
    }

    /**
     * 获取玩家信息
     */
    public getPlayer(): Player {
        return this.player;
    }
}